﻿#region Summary

// 
// Owner : JackieHan 
// 
// Solution : Skomart.Spider
// 
// Project : Jackie.Utility
// 
// File : ExtensionCollection.cs
// 
// CopyRight : Copyright © 2010-2011 Skomart Corporation, All Rights Reserved 
// 
// Summary : 扩展Collection
// 
// History : 
//			2010-10-22 15:03:55	    Create 
// 

#endregion

#region Using

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

#endregion

namespace Jackie.Utility.CustomExtension
{
    /// <summary>
    /// 对集合操作进行扩充
    /// </summary>
    public static class ExtensionCollection
    {
        public static void AddRange<T>(this ICollection<T> list, ICollection<T> childList)
        {
            foreach (T child in childList)
            {
                list.Add(child);
            }
        }

        /// <summary>
        /// 是否包含（用Id属性判断）
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        /// <param name="t"></param>
        /// <returns></returns>
        public static bool ContainsById<T>(this IEnumerable<T> list, T t) where T : BaseEntity
        {
            return list.Any(item => item.Id == t.Id);
        }

        /// <summary>
        /// 集合Distinct
        /// </summary>
        /// <typeparam name="TSource">集合类型</typeparam>
        /// <typeparam name="TKey">Distinct属性名</typeparam>
        /// <param name="source">集合</param>
        /// <param name="distinctKey">给定Key属性名</param>
        /// <returns></returns>
        public static IEnumerable<TSource> Distinct<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> distinctKey)
        {
            var distinctCollection = new List<TSource>();
            source.ForEach(item =>
            {
                TKey key = distinctKey.Invoke(item);
                if (!distinctCollection.Select(distinctKey).Contains(key))
                {
                    distinctCollection.Add(item);
                }
            });
            return distinctCollection;
        }

        public static void ForEach<T>(this IEnumerable<T> collection, Action<T> method)
        {
            foreach (T item in collection)
            {
                method(item);
            }
        }

        public static void ForEach<T>(this IEnumerable collection, Action<T> method) where T : class
        {
            foreach (object item in collection)
            {
                var tItem = item as T;
                method(tItem);
            }
        }

        public static T[] ToArray<T>(this IList<T> list)
        {
            var array = new T[list.Count];
            int i = 0;
            (list).ForEach(delegate(T item)
            {
                array[i] = item;
                i++;
            });
            return array;
        }
    }
}
